import request from "@/utils/http"
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      total: 0,
      dataSource: [],
      queryFormData: {},
      moreNum: 0,
      allowUse: true
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  onReachBottom() {
    this.reload()
  },
  methods: {
    reload() {
      if (this.dataSource.length < this.total) {
        this.pageNo = this.pageNo + 1
        this.postMethodsList(this.queryFormData)
      } else {
        this.moreNum = this.moreNum + 1
        if (this.moreNum === 1) {
          this.$toast('没有更多数据了')
        }
      }
    },
    scrollToLower() {
      this.reload()
    },
    deepDataCopy(data) {
      let obj = {}
      for (let key in data) {
        if (typeof data[key] !== 'undefined' && data[key] !== null && data[key] !== '' && data[key].length !== 0) {
          obj[key] = data[key]
        }
      }
      return obj
    },
    search(formData) {
      this.allowUse = false
      this.queryFormData = this.deepDataCopy(formData)
      this.pageNo = 1; // 重置页码
      this.dataSource = []; // 清空数据源
      this.moreNum = 0
      this.postMethodsList(this.queryFormData)
    },
    async postMethodsList(data) {
      let method = 'post'
      this.allowUse = false
      const formData = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...data
      }
      this.$showLoading("查询中...")
      try {
        const res = await request({
          url: this.restfulApi,
          method,
          data: formData
        })
        uni.stopPullDownRefresh()
        this.$hideLoading()

        // 处理 afterHandleData 的结果
        const handleAfterData = async (res) => {
          if (this.afterHandleData) {
            const result = this.afterHandleData(res)
            // 判断是否是 Promise
            if (result instanceof Promise) {
              return await result
            }
            return result
          }
          return res
        }

        // 使用处理后的数据
        const resData = await handleAfterData(res)
        let newData
        if (resData instanceof Array) {
          newData = resData
        } else {
          newData = resData.data.list || []
          this.total = resData && +resData.data.total || 0
        }
        if (this.beforeRenderList) {
          this.beforeRenderList(newData, (records) => {
            this.dataSource = this.dataSource.concat(records)
          })
        } else {
          this.dataSource = this.dataSource.concat(newData)
        }
      } catch (error) {
        uni.stopPullDownRefresh()
        this.$hideLoading()
      } finally {
        this.allowUse = true
      }
    }
  }
}
